#include "widget.h"
#include "ui_widget.h"
#include <QNetworkDatagram>

const QString SERVER_IP="127.0.0.1";
const qint16 SERVER_PORT=9090;

Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
    ui->setupUi(this);
    setWindowTitle("客户端");

    udpsocket=new QUdpSocket(this);
    connect(udpsocket,&QUdpSocket::readyRead,this,&Widget::handle);

}

Widget::~Widget()
{
    delete ui;
}


void Widget::on_pushButton_clicked()
{
    //获取输入框内容
    const QString& text=ui->lineEdit->text();
    QNetworkDatagram requestdatagram(text.toUtf8(),QHostAddress(SERVER_IP),SERVER_PORT);
    udpsocket->writeDatagram(requestdatagram);
    ui->listWidget->addItem("客户端说："+text);
    ui->lineEdit->setText("");
}

void Widget::handle()
{
    //获取响应
    QNetworkDatagram responsdatagram=udpsocket->receiveDatagram();
    QString text=responsdatagram.data();
    ui->listWidget->addItem("服务器说："+text);
}
